<template>
	<a-drawer :visible="drawerVisible" title="请选择公司" class="login-drawer" :footer="false">
		<template #header="header">
			<span>请选择公司</span>
			<div>
				<a-button @click="drawerVisible = false">取消</a-button>
				<a-button type="primary" @click="handleLogin" :disabled="!dataIndex">确认选择</a-button>
			</div>
		</template>
		<div class="data-list">
			<div :class="['item', { 'item-style': dataIndex === item.id }]" v-for="item in dataList" :key="item.id" @click="dataIndex = item.id">
				<img :src="item.logo" alt="" v-if="item.logo" class="logo" />
				{{ item.name }}
			</div>
		</div>
	</a-drawer>
</template>
<script lang="ts" setup>
import * as Api from "@/api/login";
import mitt from "@/utils/bus";
import { useMenu } from "@/store/modules/useMenu";

const { wsCache } = useCache();
const route = useRoute();
const router = useRouter();
const drawerVisible = ref(false);
const loginInfo = ref(null); // 登录信息
const dataIndex = ref(null);
const dataList = ref([]); // 租户列表

// 获取登录信息
mitt.on("loginInfo", (e) => {
	loginInfo.value = { ...e };
	getTenantList();
});

// 获取租户列表
const getTenantList = async () => {
	try {
		let res = await Api.ApiGetTenantList({ username: loginInfo.value.username });
		if (res) {
			dataIndex.value = res.find((item) => item.isLastLogin)?.id;
			if (res.length === 1) {
				dataIndex.value = res[0].id;
				wsCache.set("TENANT_ID", dataIndex.value);
				handleLogin();
			} else if (res.length > 1) {
				drawerVisible.value = true;
			}
		}
		dataList.value = res || [];
	} catch (err) {
		console.log("err===", err);
	}
};

// 登录
const handleLogin = async () => {
	wsCache.set("TENANT_ID", dataIndex.value);
	try {
		const res = await Api.ApiLogin(loginInfo.value);
		if (res?.accessToken) {
			wsCache.set("userInfo", res);
			wsCache.set("ACCESS_TOKEN", res.accessToken);
			const menuStore = useMenu();
			await menuStore.addRoutes();
			router.push("/customer/0");
		}
	} catch (err) {
		console.log("err===", err);
	}
};

defineExpose({
	drawerVisible
});
</script>
<style lang="scss" scoped>
.data-list {
	display: flex;
	flex-direction: column;
	row-gap: 20px;
	.item {
		padding: 20px;
		cursor: pointer;
		border: 1px solid #424242;
		color: rgba(255, 255, 255, 0.85);
		font-size: 16px;
		font-weight: bold;
		border-radius: 6px;
		background: #141414;
		display: flex;
		align-items: center;
		.logo {
			width: 100px;
			margin-right: 20px;
		}
		&-style {
			background: #111a2c;
			border: 1px solid #1668dc;
		}
	}
}
</style>
<style lang="scss">
.login-drawer {
	.arco-drawer {
		width: 500px !important;
		background-color: #1f1f1f;
		&-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
		.arco-drawer-header {
			border-bottom: 1px solid rgba(253, 253, 253, 0.12);
			padding: 10px 15px;
			font-size: 14px;
			font-weight: bold;
			color: rgba(255, 255, 255, 0.85);
		}
	}
}
</style>
